<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

/**
 * @property int $id
 * @property string $question
 * @property int $type
 * @property string $type_name
 * @property int $category_id
 * @property int $status
 * @property string $answer
 * @property array $answer_array
 * @property string $option_1
 * @property string $option_2
 * @property string $option_3
 * @property string $option_4
 */
class Question extends Model
{
    // 单选
    const TYPE_OF_RADIO = 0;

    // 多选
    const TYPE_OF_CHECKBOX = 1;

    // 判断
    const TYPE_OF_TF = 2;

    /**
     * 从缓存中获取题目
     *
     * @param int|array $id
     * @return Question|Question[]
     */
    public static function getFromCache($id)
    {
        $question = Cache::store()->tags('questions')->rememberForever($id, function () use ($id) {
            return self::query()->find($id);
        });

        if (is_array($id) && in_array(null, $question)) {
            $unCacheIds = array_keys(array_filter($question, function ($item) {
                return is_null($item);
            }));

            foreach ($unCacheIds as $unCacheId) {
                $question[$unCacheId] = static::getFromCache((int) $unCacheId);
            }
        }

        return $question;
    }

    /**
     * 获取题目类型
     *
     * @return string
     */
    public function getTypeNameAttribute()
    {
        switch ($this->type) {
            case self::TYPE_OF_RADIO: return '选择题';
            case self::TYPE_OF_CHECKBOX: return '多选题';
            case self::TYPE_OF_TF: return '判断题';
            default: return '未知题型';
        }
    }

    /**
     * 获取答案
     *
     * @return string[]
     */
    public function getAnswerArrayAttribute()
    {
        $value = explode(',', $this->answer);

        sort($value);

        return $value;
    }

    /**
     * 题库分类
     *
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}
